package week07.necessary.aop;


import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import week07.necessary.annotation.DsReadOnly;
import week07.necessary.config.DatasourceContextHolder;

@Aspect
@Component
@RequiredArgsConstructor
public class DynamicDatasourceAspect {
    private final DatasourceContextHolder contextHolder;

    @Pointcut("@annotation(week07.necessary.annotation.DsReadOnly)")
    public void annotationPointcut() {
    }


    @Around("annotationPointcut()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            DsReadOnly annotation = signature.getMethod().getAnnotation(DsReadOnly.class);
            if (annotation != null) {
                contextHolder.setContext(annotation.ds());
            }
            return joinPoint.proceed();
        } finally {
            contextHolder.clearContext();
        }
    }
}
